import { Descriptions, Modal, Image } from 'antd';
import { forwardRef, memo, useImperativeHandle, useState } from 'react';
import FileUtil from '@/utils/file.js';
import { getName } from '@/pages/FileManage/fun.js';
import { VideoPlayer } from '@/components/index.jsx';
import { useUpdateEffect } from 'ahooks';

const FileModal = forwardRef((_, ref) => {
  useImperativeHandle(ref, () => ({
    open: (data) => {
      setOpen(true);
      setData(data);
    }
  }));

  const [data, setData] = useState({});
  const [open, setOpen] = useState(false);
  const [width, setWidth] = useState(300);
  const items = [
    {
      key: '1',
      label: '文件名称',
      children: <>{getName(data)}</>
    },
    {
      key: '100',
      label: '原始名称',
      children: <>{data?.originalName ?? '-'}</>
    },
    {
      key: '2',
      label: '媒体类型',
      children: <>{data?.mediaType ?? '-'}</>
    },
    {
      key: '3',
      label: '文件大小',
      children: <>{FileUtil.formatFileSize(data?.size)}</>
    },
    {
      key: '4',
      label: '上传者ID',
      children: <>{data?.uploadUserId ?? '-'}</>
    },
    {
      key: '5',
      label: '创建时间',
      children: <>{data?.createTime ?? '-'}</>
    },
    {
      key: '6',
      label: '更新时间',
      children: <>{data?.updateTime ?? '-'}</>
    }
  ];

  useUpdateEffect(() => {
    if (
      typeof data?.mediaType === 'string' &&
      (data?.mediaType.includes('video/') || data?.mediaType.includes('image/'))
    ) {
      setWidth(500);
    } else {
      setWidth(300);
    }
  }, [data]);

  if (typeof data?.mediaType === 'string' && data?.mediaType.includes('image/')) {
    items.unshift({
      label: '预览',
      children: (
        <>
          <Image src={`/v/${data?.encryptionId}`} height={200} />
        </>
      ),
      key: '100'
    });
  } else if (typeof data?.mediaType === 'string' && data?.mediaType.includes('video/')) {
    items.unshift({
      label: '预览',
      children: (
        <>
          <VideoPlayer src={`/v/${data?.encryptionId}`} height={230} />
        </>
      ),
      key: '100'
    });
  }

  return (
    <>
      <Modal
        destroyOnClose
        open={open}
        title="文件详情"
        width={width}
        cancelText="关闭"
        onCancel={() => setOpen(false)}
        okButtonProps={{ style: { display: 'none' } }}
      >
        <Descriptions column={1} items={items} />
      </Modal>
    </>
  );
});

export default memo(FileModal);
